package cn.wolfcode.luowowo.mgrsite.job;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.vo.StatisVO;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * spring定时器   用于将redis数据持久化到MySQL
 */
//@Component
public class RedisDataPersistenceJob {

    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;

    @Reference
    private IStrategyDetailService strategyDetailService;


    //@Scheduled 定时任务标签
    //cron 定时任务计划  指定定时任务执行时间周期
    @Scheduled(cron = "0/20 * * * * ?")
    public void doWork(){
        System.out.println("----------vo的持久化----  start---");
        //查询出所有vo
       List<StrategyStatisVO> list= strategyStatisRedisService.listVo(RedisKeys.STRATGY_STATIS_VO.join("*"));

        //updata 到数据库中
        for (StrategyStatisVO vo :list){
            StatisVO statisVO = new StatisVO();

            BeanUtils.copyProperties(vo,statisVO);
            strategyDetailService.updateStatisVo(statisVO);
        }



        System.out.println("----------vo的持久化--end----------");

        System.out.println("----------zset的持久化--start----------");
        //热门初始化
        for (StrategyStatisVO detail:list){
            String voId= RedisKeys.STRATGY_STATIS_VO.join(detail.getDestId() .toString());
            String zsetKey = RedisKeys.STRATEGY_HOT_ZSET.getPrefix();

            //判断某个void是否存在指定的zset中
            if (strategyStatisRedisService.isVoidExistZset(voId,zsetKey)){
                continue;
            }
            int score = detail.getViewnum()+detail.getReplynum();
            strategyStatisRedisService.addScoreHot(detail.getDestId(),score);
        }

        //国外排行初始化
        //热门初始化
        for (StrategyStatisVO detail:list){
            String voId= RedisKeys.STRATGY_STATIS_VO.join(detail.getDestId() .toString());
            String zsetKey = null;
            if (detail.isIsabroad()){
                zsetKey = RedisKeys.STRATEGY_ABROAD_ZSET.getPrefix();
            }else{
                zsetKey = RedisKeys.STRATEGY_CHINA_ZSET.getPrefix();
            }




            //判断某个void是否存在指定的zset中
            if (strategyStatisRedisService.isVoidExistZset(voId,zsetKey)){
                continue;
            }
            int score = detail.getThumbsupnum()+detail.getFavornum();
            strategyStatisRedisService.addScoreHot(detail.getDestId(),score);
        }

        System.out.println("----------zset的持久化--end----------");
    }
}
